import { useRef, useState } from 'react';

import { useAntdTable } from 'ahooks';
import {
  Button,
  DatePicker,
  Popconfirm,
  Space,
  Table,
  TableColumnsType,
  Upload,
  UploadFile
} from 'antd';
import dayjs from 'dayjs';
import Saver from 'file-saver';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import { TimeSort } from '@/enum';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { proShiftTeamPage } from '@/services/bizApi/shengchanbanzujiekou';
import {
  proIndicatorDataDelete,
  proIndicatorDataList
} from '@/services/bizApi/shengchanzhibiaoshujujiekou';
import {
  proIndicatorInfoDelete,
  proIndicatorInfoDownloadTemplate,
  proIndicatorInfoPage
} from '@/services/bizApi/shengchanzhibiaoxinxijiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import Edit, { EditRef } from './edit';
import EditTeam, { EditTeamRef } from './editTeam';

/** 该模块增删改查对象 */
export type BizObject = BIZAPI.ProIndicatorInfoEntity;

/**子表数据 */
export type SubObject = BIZAPI.ProIndicatorDataEntity;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const editTeam = useRef<EditTeamRef>(null);
  const [filter] = Filter.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [expandDataSource, setExpandDataSource] = useState<SubObject[]>([]);
  const expandedRowKeys = useRef<string[]>([]);

  const table = useAntdTable(
    async ({ current, pageSize }, { id, ...formData }) => {
      const res = await proIndicatorInfoPage({
        ...formData,
        ...id,

        reportTimeBegin: formData.reportDate
          ? dayjs(formData.reportDate?.[0]).format('YYYY-MM-DD')
          : undefined,
        reportTimeEnd: formData.reportDate
          ? dayjs(formData.reportDate?.[1]).format('YYYY-MM-DD')
          : undefined,
        page: current,
        size: pageSize,
        timeSort: TimeSort.倒序
      });

      return {
        list: res.data?.records || [],
        total: res.data?.total || 0
      };
    },
    {
      form: filter
    }
  );

  const columns: TableColumnsType<BizObject> = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      align: 'center',
      render: (_, row, index) => index + 1
    },
    {
      title: '班组名称',
      dataIndex: 'teamName'
    },
    {
      title: '填报人',
      dataIndex: 'reporterName'
    },
    {
      title: '值班时间',
      dataIndex: 'dutyStartTime',
      key: 'dutyStartTime',
      render: (text, reacord) => (
        <div>
          {dayjs(reacord.dutyStartTime).format('YYYY-MM-DD HH:mm:ss')} -{' '}
          {dayjs(reacord.dutyEndTime).format('YYYY-MM-DD HH:mm:ss')}
        </div>
      )
    },
    {
      title: '操作',
      fixed: 'right',
      align: 'center',
      render: (_, row) => {
        function equDefectAcceptanceSubmit(arg0: { id: string }) {
          throw new Error('Function not implemented.');
        }

        return (
          <Text.Space>
            {permission.check() && (
              <Text
                onClick={async () => {
                  edit.current?.open({
                    type: 'add',
                    infoId: row.id as unknown as string,
                    onSuccess: () => {
                      getExpandDataSource(row.id!);
                    }
                  });
                }}
                type="primary"
              >
                新增指标数据
              </Text>
            )}
            {permission.check() && (
              <Text
                onClick={() => {
                  editTeam.current?.open({
                    type: 'edit',
                    rowData: row,
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                编辑
              </Text>
            )}
            {permission.check() && (
              <Popconfirm
                title={`确定删除该条指标填报吗？`}
                onConfirm={async () => {
                  const res = await proIndicatorInfoDelete({
                    id: row.id as unknown as string
                  });

                  store.app?.message.success('删除成功');
                  table.refresh();
                }}
              >
                <Text type="danger">删除</Text>
              </Popconfirm>
            )}
          </Text.Space>
        );
      }
    }
  ];

  const getExpandDataSource = async (infoId: number) => {
    const resData = await proIndicatorDataList({
      infoId
    });
    setExpandDataSource(resData.data || []);
  };

  const expandColumns: TableColumnsType<SubObject> = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      render: (_, row, index) => index + 1,
      width: 60,
      align: 'center'
    },

    { title: '填报时间', dataIndex: 'reportTime', key: 'reportTime', width: 150 },
    {
      title: '工艺消耗',
      children: [
        { title: '原辅料吨水消耗（元/t)', dataIndex: 'yfldsxh', key: 'yfldsxh', width: 180 },
        { title: '电能吨水消耗（元/t)', dataIndex: 'dndsxh', key: 'dndsxh', width: 180 },
        { title: '自来水吨水消耗（元/t)', dataIndex: 'zlsdsxh', key: 'zlsdsxh', width: 180 }
      ]
    },
    {
      title: '一、二级DO控制',
      children: [
        { title: '生化A线一级O溶氧(mg/l)', dataIndex: 'shaxyjory', key: 'shaxyjory', width: 180 },
        { title: '生化A线二级O溶氧(mg/l)', dataIndex: 'shaxejory', key: 'shaxejory', width: 180 },
        { title: '生化B线一级O溶氧(mg/l)', dataIndex: 'shbxyjory', key: 'shbxyjory', width: 180 },
        { title: '生化B线二级O溶氧(mg/l)', dataIndex: 'shbxejory', key: 'shbxejory', width: 180 }
      ]
    },
    {
      title: 'MBR膜池运行稳定性',
      children: [
        { title: 'MBR膜池液位A1(米)', dataIndex: 'mbrmcywa1', key: 'mbrmcywa1', width: 180 },
        { title: 'MBR膜池液位A2(米)', dataIndex: 'mbrmcywa2', key: 'mbrmcywa2', width: 180 },
        { title: 'MBR膜池液位B1(米)', dataIndex: 'mbrmcywb1', key: 'mbrmcywb1', width: 180 },
        { title: 'MBR膜池液位B2(米)', dataIndex: 'mbrmcywb2', key: 'mbrmcywb2', width: 180 }
      ]
    },
    {
      title: 'Fendon产水COD控制效果',
      children: [{ title: '芬顿出水cod(mg/l)', dataIndex: 'fdcscod', key: 'fdcscod', width: 180 }]
    },
    {
      title: '气浮刮泥控水指标',
      children: [
        { title: '气浮进水ss(mg/l)', dataIndex: 'qfjsss', key: 'qfjsss', width: 180 },
        { title: '气浮出水ss(mg/l)', dataIndex: 'qfcsss', key: 'qfcsss', width: 180 },
        { title: '气浮进水量(mg/l)', dataIndex: 'qfjsl', key: 'qfjsl', width: 180 },
        { title: '气浮刮渣含水率(%)', dataIndex: 'qfgzhsl', key: 'qfgzhsl', width: 180 },
        { title: '污泥池液变化值(t)', dataIndex: 'wncybhz', key: 'wncybhz', width: 180 },
        { title: '离心机进料量(t)', dataIndex: 'lxjjll', key: 'lxjjll', width: 180 }
      ]
    },
    {
      title: '处理水量效率',
      children: [
        { title: '生化实际处理值(t)', dataIndex: 'shsjclz', key: 'shsjclz', width: 180 },
        { title: '工艺指定生化处理量(t)', dataIndex: 'gyzdshclz', key: 'gyzdshclz', width: 180 }
      ]
    },
    {
      title: '在线检测排放指标超标',
      children: [
        { title: 'BAF 出水cod(mg/l)', dataIndex: 'bafcscod', key: 'bafcscod', width: 180 },
        { title: 'BAF出水氨氮(mg/l)', dataIndex: 'bafcsad', key: 'bafcsad', width: 180 }
      ]
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 200,
      align: 'center',
      render: (_, row) => (
        <Space size="middle">
          {permission.check() && (
            <Text
              onClick={() => {
                edit.current?.open({
                  type: 'edit',
                  rowData: row,
                  infoId: row.infoId as unknown as string,
                  onSuccess: () => {
                    getExpandDataSource(row.infoId!);
                  }
                });
              }}
              type="primary"
            >
              编辑
            </Text>
          )}
          {permission.check() && (
            <Popconfirm
              title={`确定删除该条指标数据吗？`}
              onConfirm={async () => {
                const res = await proIndicatorDataDelete({
                  id: row.id as unknown as string
                });

                store.app?.message.success('删除成功');
                getExpandDataSource(row.infoId!);
              }}
            >
              <Text type="danger">删除</Text>
            </Popconfirm>
          )}
        </Space>
      )
    }
  ];

  const expandedRowRender = () => (
    <Table<SubObject>
      columns={expandColumns}
      size="small"
      bordered
      rowKey="id"
      tableLayout="fixed"
      virtual={true}
      dataSource={expandDataSource}
      pagination={false}
    />
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            {permission.check() && (
              <Button
                onClick={() => {
                  editTeam.current?.open({
                    type: 'add',
                    onSuccess: () => {
                      table.refresh();
                    }
                  });
                }}
                type="primary"
              >
                新增填报
              </Button>
            )}
            {permission.check() && (
              <Button
                onClick={async () => {
                  const res = await proIndicatorInfoDownloadTemplate({
                    skipErrorHandler: true,
                    responseType: 'blob'
                  });
                  Saver.saveAs(res?.data, '指标填报模板.xlsx');
                }}
                type="primary"
              >
                下载模板
              </Button>
            )}
            {permission.check() && (
              <Upload
                maxCount={1}
                accept=".xls,.xlsx"
                showUploadList={false}
                beforeUpload={() => false}
                fileList={fileList}
                onChange={(info) => {
                  setFileList(info.fileList);
                  if (info.fileList.length) {
                    editTeam.current?.handleImport({
                      file: info.fileList[0] as UploadFile,
                      onSuccess: () => {
                        alert(3);
                        table.refresh();
                      }
                    });
                  }
                }}
              >
                <Button type="primary">导入</Button>
              </Upload>
            )}
          </>
        }
      >
        <ProFormSelect
          name="productionSite"
          label=""
          placeholder="请选择班组名称"
          style={{ width: 180 }}
          request={async () => {
            const res = await proShiftTeamPage({
              page: 1,
              size: 1000
            });
            return (
              res.data?.records?.map((item) => ({
                value: item.id,
                label: item.name
              })) || []
            );
          }}
        />
        <Filter.Item name="reportDate">
          <DatePicker.RangePicker placeholder={['填报时间', '填报时间']} />
        </Filter.Item>
        <ProFormSelect
          name="reporterId"
          style={{ width: 180 }}
          label=""
          placeholder="填报人"
          showSearch={true}
          request={async () => {
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000
            });
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      {/* 表格 */}
      <Table<BizObject>
        size="small"
        columns={columns}
        expandable={{
          expandedRowRender,
          // defaultExpandedRowKeys: ['0'],
          expandedRowKeys: expandedRowKeys.current,
          onExpand: async (expanded, record) => {
            if (expanded) {
              expandedRowKeys.current = [record.id! as unknown as string];
              getExpandDataSource(record.id!);
            } else {
              expandedRowKeys.current = [];
            }
          }
        }}
        scroll={{
          x: 'max-content'
        }}
        rowKey="id"
        bordered
        {...table.tableProps}
        pagination={{
          ...table.tableProps.pagination,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50', '100']
        }}
      />
      {/* end表格 */}

      <Edit ref={edit} />
      <EditTeam ref={editTeam} />
    </>
  );
};

export default Page;
